//
//  UpdatePhoneController.swift
//  TrafficViolation
//
//  Created by eaglelive on 2017/4/16.
//  Copyright © 2017年 eaglelive. All rights reserved.
//

import Foundation
import UIKit
import Alamofire
import SwiftyJSON
class UpdatePhoneController: BaseController {
    var personal:PersonalModel!//个人信息
    var oldPhone,userPhone,verifyCode,userPwd:UITextField!//用户名密码
    var codebutton : UIButton!
    let textX:CGFloat = 20
    let textWidth:CGFloat = kScreenW - 40
    
    var remainingSeconds: Int = 0 {
        willSet {
            codebutton.setTitle("\(newValue)秒后重新获取", for: .normal)
            codebutton.titleLabel?.font = UIFont.systemFont(ofSize: 10)
            if newValue <= 0 {
                codebutton.setTitle("获取验证码", for: .normal)
                codebutton.titleLabel?.font = UIFont.systemFont(ofSize: 12)
                isCounting = false
            }
        }
    }
    
    var isCounting = false {
        willSet {
            if newValue {
                countdownTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.updateTime), userInfo: nil, repeats: true)
                remainingSeconds = 60
                codebutton.backgroundColor = UIColor.lightGray
            } else {
                countdownTimer?.invalidate()
                countdownTimer = nil
                codebutton.backgroundColor = appMainColor
            }
            codebutton.isEnabled  = !newValue
        }
    }
    var countdownTimer: Timer?
    
    override func viewDidLoad(){
        super.viewDidLoad()
        setupNavBar(title: "更改手机号码", isback: true, appearWay: 3, isright: false)//自定义导航

        userPhone = UITextField(frame: CGRect(x:textX, y:getCellY(index: 0) + 10, width:textWidth, height:cellH))
        userPhone.placeholder = "请输入新手机号码"
        userPhone.autocapitalizationType = .none
        //设置左边小图片
        let phoneLeftView:UIView=UIView(frame: CGRect(x:0, y:0, width:30, height:cellH));
        let leftImage0:UIImageView=UIImageView(frame: CGRect(x:5,y:10, width:15, height:22));
        leftImage0.image=UIImage(named: "user_phone");
        phoneLeftView.addSubview(leftImage0)
        userPhone.leftView = phoneLeftView//  设置左边小图片
        userPhone.leftViewMode = UITextFieldViewMode.always
        self.view.addSubview(userPhone)
        //分割线
        self.view.addSubview(getSeparator(index: 1))
        //验证码
        verifyCode = UITextField(frame: CGRect(x:textX, y:getCellY(index: 1) + 10, width:textWidth, height:cellH))
        verifyCode.placeholder = "请输入短信验证码"
        //设置左边小图片
        let codeLeftView:UIView=UIView(frame: CGRect(x:0, y:0, width:30, height:cellH));
        let codeimage:UIImageView=UIImageView(frame: CGRect(x:5,y:10, width:18, height:20));
        codeimage.image=UIImage(named: "verification_code");
        codeLeftView.addSubview(codeimage)
        verifyCode.leftView = codeLeftView//  设置左边小图片
        verifyCode.leftViewMode = UITextFieldViewMode.always
        self.view.addSubview(verifyCode)
        //分割线
        self.view.addSubview(getSeparator(index: 2))
        //设置右边按钮
        let codeRightView:UIView=UIView(frame: CGRect(x:0, y:0, width:80, height:cellH))
        codebutton = UIButton(frame: CGRect(x:0,y:0, width:80, height:30))
        codebutton.layer.cornerRadius = 10
        codebutton.setTitle("获取验证码", for:.normal)
        codebutton.titleLabel?.font = UIFont.systemFont(ofSize: 12)
        codebutton.backgroundColor = appMainColor
        codebutton.addTarget(self, action: #selector(verifyCodeClick(sender:)), for: UIControlEvents.touchUpInside)
        codeRightView.addSubview(codebutton)
        verifyCode.rightView = codeRightView//  设置右边按钮
        verifyCode.rightViewMode = UITextFieldViewMode.always
        self.view.addSubview(verifyCode)
        //分割线
        self.view.addSubview(getSeparator(index: 3))
        //密码
        userPwd = UITextField(frame: CGRect(x:textX, y:getCellY(index: 2) + 10, width:textWidth, height:cellH))
        userPwd.placeholder = "请输入登录密码"
        userPwd.autocapitalizationType = .none
        let pwdLeftView:UIView=UIView(frame: CGRect(x:0, y:0, width:30, height:cellH));
        let leftImage2:UIImageView=UIImageView(frame: CGRect(x:5,y:10, width:18, height:20));
        leftImage2.image=UIImage(named: "password");
        pwdLeftView.addSubview(leftImage2)
        userPwd.leftView = pwdLeftView//  设置左边小图片
        userPwd.leftViewMode = UITextFieldViewMode.always
        userPwd.isSecureTextEntry = true
        self.view.addSubview(userPwd)
        //分割线
        self.view.addSubview(getSeparator(index: 4))
        
        oldPhone = UITextField(frame: CGRect(x:textX, y:getCellY(index: 3) + 10, width:textWidth, height:cellH))
        oldPhone.placeholder = "请输入旧手机号码"
        oldPhone.autocapitalizationType = .none
        //设置左边小图片
        let oldLeftView:UIView=UIView(frame: CGRect(x:0, y:0, width:30, height:cellH));
        let leftImage:UIImageView=UIImageView(frame: CGRect(x:5,y:10, width:15, height:22));
        leftImage.image=UIImage(named: "user_phone");
        oldLeftView.addSubview(leftImage)
        oldPhone.leftView = oldLeftView//  设置左边小图片
        oldPhone.leftViewMode = UITextFieldViewMode.always
        self.view.addSubview(oldPhone)
        //分割线
        self.view.addSubview(getSeparator(index: 1))
        
        
        let button:UIButton = UIButton(type:.custom)
        button.frame = CGRect(x:textX, y:getCellY(index: 4) + cellH, width:textWidth, height:cellH)//设置登陆按钮位置和大小
        button.layer.cornerRadius = 10;
        button.backgroundColor = appMainColor
        button.showsTouchWhenHighlighted = true //
        button.adjustsImageWhenHighlighted=false ////使触摸模式下按钮也不会变暗（半透明
        button.setTitle("确定", for:.normal)
        button.addTarget(self, action: #selector(confirmBtnClick(sender:)), for: UIControlEvents.touchUpInside)
        self.view.addSubview(button)
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
}
extension UpdatePhoneController{
    
    func getCellY(index : Int) -> CGFloat {
        return 50 * CGFloat(index) + kStatusBarH + kNavigationBarH + 20
    }
    
    func getSeparator(index: Int) -> UILabel {
        let lab = UILabel.init(frame: CGRect(x: textX, y: getCellY(index: index), width: textWidth, height: 1))
        lab.backgroundColor = separatorColor
        return lab
    }
    
    func updateTime(timer: Timer) {
        // 计时开始时，逐秒减少remainingSeconds的值
        remainingSeconds -= 1
    }
    
    func confirmBtnClick(sender: UIButton) {
        if "" == oldPhone.text! || "" == userPwd.text! || "" == userPhone.text! || "" == verifyCode.text! {
            checkAlertFun(message: "信息填写不全！")
        }else{
           confirmFunc()
        }
    }
    //提交信息
    func confirmFunc() {
        if reachability.isReachable {
            let parameter:[String:Any] = [
                "oldPhoneNum":oldPhone.text!,
                "oldPasswd":userPwd.text!
            ]
            Alamofire.request("\(projectUrl)/user/changeUserPhoneNum/\(userID!)/\(userPhone.text!)/\(verifyCode.text!)/?tokenID=\(tokenID!)&tokenUserID=\(userID!)",method:.post, parameters:parameter,headers:headers).responseJSON { (response) in
                let jsonString = response.result.value!
                let jsonDate = JSON(jsonString)
                print(jsonDate)
                if jsonDate["success"] == true {
                    let alertController = UIAlertController(title: alertTitle, message: "手机号码修改成功！", preferredStyle: .alert)
                    let okAction = UIAlertAction(title: "重新登录", style: .default, handler:{
                        (UIAlertAction) -> Void in
                        let mainVC = UINavigationController(rootViewController: LoginController())
                        app.window?.rootViewController = mainVC
                    })
                    alertController.addAction(okAction)
                    self.present(alertController, animated: true, completion: nil)
                }else{
                    self.failOperNoticeFun(code: jsonDate["rcode"].rawString()!, message: jsonDate["rdata"].rawString()!)
                }
            }
        }else{
            let alertController = UIAlertController(title: alertTitle, message: netNotice, preferredStyle: .alert)
            let cancelAction = UIAlertAction(title: "确定", style: .cancel, handler: nil)
            alertController.addAction(cancelAction)
            self.present(alertController, animated: true, completion: nil)
        }
    }
    //获取验证码
    func verifyCodeClick(sender: UIButton){
        if("" != userPhone.text!){
            if reachability.isReachable {
                isCounting = true
                Alamofire.request("\(projectUrl)/user/changeUserPhoneNum/code/\(userPhone.text!)/?tokenID=\(tokenID!)&tokenUserID=\(userID!)",method:.post, parameters:nil,headers:headers).responseJSON { (response) in
                    let jsonString = response.result.value!
                    let jsonDate = JSON(jsonString)
                    print("jsonDate:\(jsonDate)")
                    if jsonDate["success"] == false {
                        self.failOperNoticeFun(code: jsonDate["rcode"].rawString()!, message: jsonDate["rdata"].rawString()!)
                    }
                }
            }else{
                let alertController = UIAlertController(title: alertTitle, message: netNotice, preferredStyle: .alert)
                let cancelAction = UIAlertAction(title: "确定", style: .cancel, handler: nil)
                alertController.addAction(cancelAction)
                self.present(alertController, animated: true, completion: nil)
            }
        }else{
            let alertController = UIAlertController(title: alertTitle, message: "请输入手机号码！", preferredStyle: .alert)
            let cancelAction = UIAlertAction(title: "确定", style: .cancel, handler: nil)
            alertController.addAction(cancelAction)
            self.present(alertController, animated: true, completion: nil)
        }
        
    }
}

